package com.ssyc.student.adapter;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.github.aakira.expandablelayout.ExpandableLayout;
import com.github.aakira.expandablelayout.ExpandableLayoutListenerAdapter;
import com.github.aakira.expandablelayout.ExpandableRelativeLayout;
import com.github.aakira.expandablelayout.Utils;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.MediaPlayerManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.student.R;
import com.ssyc.student.activity.StudentVocabularyPrepareSecondActivity;
import com.ssyc.student.activity.StudentVocabularyPrepareThirdActivity;
import com.ssyc.student.bean.CloneWordPrepareInfo;
import com.ssyc.student.bean.ResultInfo;
import com.ssyc.student.bean.WordPrepareInfo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 学生端--词汇预习--列表适配器
 * Created by Administrator on 2018/5/7 0007.
 */

public class StVocablaryPreviewRvAdapter extends BaseQuickAdapter<WordPrepareInfo.DataBean.QuestionListBean, BaseViewHolder> {

    private final List<WordPrepareInfo.DataBean.QuestionListBean> data;
    //克隆的数据,解决TimeInterpolator不能传递的问题
    private final List<CloneWordPrepareInfo.DataBean.QuestionListBean> cloneData;
    private Context context;

    //LeesonId和GradeId
    private String lessonId, gradeId;

    //收藏与取消收藏的接口
    private String url = "";

    private SparseBooleanArray expandState = new SparseBooleanArray();

    public StVocablaryPreviewRvAdapter(String lessonId, String gradeId, Context context, int layoutResId, @Nullable List<WordPrepareInfo.DataBean.QuestionListBean> data, List<CloneWordPrepareInfo.DataBean.QuestionListBean> cloneData) {
        super(layoutResId, data);
        this.context = context;
        this.data = data;
        this.cloneData = cloneData;
        this.lessonId = lessonId;
        this.gradeId = gradeId;
        //设置默认的展开位置,默认第1个条目为展开位置s
        for (int i = 0; i < data.size(); i++) {
            if (i == 0) {
                expandState.append(i, true);
            } else {
                expandState.append(i, false);
            }
        }
    }

    @Override
    protected void convert(BaseViewHolder helper, WordPrepareInfo.DataBean.QuestionListBean item) {
        //播放单词录音的图片
        ImageView ivPlayWord = helper.getView(R.id.iv_play_voice);

        //显示单词的文本
        TextView tvWordName = helper.getView(R.id.tv_word_name);
        tvWordName.setText(item.getWordname());

        //显示音标的文本
        TextView tvWordPhonetic = helper.getView(R.id.tv_word_phonetic);
        tvWordPhonetic.setText(item.getPhonetic());

        //单词的解释
        TextView tvWordExplan = helper.getView(R.id.tv_word_explan);
        tvWordExplan.setText(item.getText());

        //收藏的布局
        RelativeLayout rlCollection = helper.getView(R.id.rl_collection);

        //显示收藏的数量
        TextView tv_conection_num = helper.getView(R.id.tv_conection_num);
        if ("2".equals(AccountUtils.getRole(context))) {
            //老师端显示单词收藏
            tv_conection_num.setVisibility(View.VISIBLE);
            tv_conection_num.setText(item.getStu_sizi() + "");
        } else {
            tv_conection_num.setVisibility(View.GONE);
        }

        //收藏的布标
        ImageView ivCollection = helper.getView(R.id.iv_collection);
        if (0 == item.getCollection()) {
            //未收藏
            ivCollection.setImageResource(R.drawable.st_collection_normal);
        } else {
            //已收藏
            ivCollection.setImageResource(R.drawable.st_collection_has_select);
        }

        //播放句子录音的图片
        ImageView ivPlaySentence = helper.getView(R.id.iv_play_sentence);

        if (!TextUtils.isEmpty(item.getExample())) {

            //切割getExample()使用特殊符号进行切割
            String[] exampleContents = item.getExample().split("￠");

            //句子的内容文本
            TextView tvSentenceName = helper.getView(R.id.tv_sentence_name);
            tvSentenceName.setText(item.getExample());

            //句子的解释
            TextView tvSentenceExplan = helper.getView(R.id.tv_sentence_explan);
            tvSentenceExplan.setVisibility(View.GONE);
//            tvSentenceExplan.setText(item.getExample_t());

//            if (null != exampleContents && exampleContents.length == 2) {
//                tvSentenceName.setText(exampleContents[0]);
//                tvSentenceExplan.setText(exampleContents[1]);
//            }
        }

        //折叠布局
        ExpandableRelativeLayout expandableLayout = helper.getView(R.id.expandableLayout);
        expandableLayout.setInterpolator(item.getInterpolator());
        expandableLayout.setExpanded(expandState.get(helper.getLayoutPosition()));

        //折叠按钮
        RelativeLayout buttonLayout = helper.getView(R.id.button);
        expandableLayout.setListener(new ExpandableLayoutListenerAdapter() {
            @Override
            public void onPreOpen() {
                createRotateAnimator(buttonLayout, 0f, 180f).start();
                expandState.put(helper.getLayoutPosition(), true);
            }

            @Override
            public void onPreClose() {
                createRotateAnimator(buttonLayout, 180f, 0f).start();
                expandState.put(helper.getLayoutPosition(), false);
            }
        });

        buttonLayout.setRotation(expandState.get(helper.getLayoutPosition()) ? 180f : 0f);

        //包含单元名称的整体相对布局
        LinearLayout llGroup = helper.getView(R.id.ll_group);
        llGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                onClickButton(expandableLayout);
            }
        });


        //设置点击事件
        ivPlayWord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //播放单词音频
                MediaPlayerManager.getInstance().play(item.getSound(), null, null);
            }
        });

        //跳转
        RelativeLayout rl_word = helper.getView(R.id.rl_word);

        //单词的点击事件
        tvWordExplan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //单词的点击事件,跳转到词汇预习界面2
                Intent intent = new Intent(context, StudentVocabularyPrepareThirdActivity.class);

                //携带clone的数据集合过去
                intent.putExtra("questioninfos", GsonUtil.listToJson(cloneData));

                //所有的单体点击进去都从给第一个开始学习
                intent.putExtra("currpos", 0);

                //携带
                intent.putExtra(StudentVocabularyPrepareSecondActivity.LESSONID, lessonId);
                intent.putExtra(StudentVocabularyPrepareSecondActivity.GRADEID, gradeId);

                context.startActivity(intent);
            }
        });

        rl_word.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //单词的点击事件,跳转到词汇预习界面2
                Intent intent = new Intent(context, StudentVocabularyPrepareThirdActivity.class);

                //携带clone的数据集合过去
                intent.putExtra("questioninfos", GsonUtil.listToJson(cloneData));

                //所有的单体点击进去都从给第一个开始学习
                intent.putExtra("currpos", 0);


                //携带
                intent.putExtra(StudentVocabularyPrepareSecondActivity.LESSONID, lessonId);
                intent.putExtra(StudentVocabularyPrepareSecondActivity.GRADEID, gradeId);

                context.startActivity(intent);
            }
        });

        //收藏的点击事件
        rlCollection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //收藏与取消收藏的操作
                doCollectionAction(item, helper.getLayoutPosition());
            }
        });

        //播放句子点击事件
        ivPlaySentence.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //播放句子的音频
                MediaPlayerManager.getInstance().play(item.getExamplesound(), null, null);
            }
        });
    }

    /**
     * 创建动画的方法
     *
     * @param target
     * @param from
     * @param to
     * @return
     */
    public ObjectAnimator createRotateAnimator(final View target, final float from, final float to) {
        ObjectAnimator animator = ObjectAnimator.ofFloat(target, "rotation", from, to);
        animator.setDuration(300);
        animator.setInterpolator(Utils.createInterpolator(Utils.LINEAR_INTERPOLATOR));
        return animator;
    }

    /**
     * 折叠布局的切换方法
     *
     * @param expandableLayout
     */
    private void onClickButton(final ExpandableLayout expandableLayout) {
        expandableLayout.toggle();
    }

    /**
     * 做收藏和取消收藏的方法
     *
     * @param item
     */
    private void doCollectionAction(WordPrepareInfo.DataBean.QuestionListBean item, int pos) {

        //收藏与取消收藏
        Map<String, String> map = new HashMap<>();
        if (item.getCollection() == 0) {
            map.put("type", "18");
        } else if (item.getCollection() == 1) {
            map.put("type", "19");
        }
        map.put("acc", AccountUtils.getAccount(context));//18062585082
        map.put("role", "0");
        map.put("gradeid", gradeId);
        map.put("lessonid", lessonId);
        map.put("moduleid", "10");
        map.put("typeid", item.getTitletype() + "");
        map.put("questionid", item.getTitle() + "");
        map.put("apptoken", AccountUtils.getToken(context));
        Log.i("test", "token:" + AccountUtils.getToken(context));
        map.put("platform", "8");


        //根据是否收藏的状态来标识请求接口
        if (item.getCollection() == 0) {
            //未收藏,请求收藏接口
            url = HttpAdress.COLLECTION;
        } else if (item.getCollection() == 1) {
            //已经收藏,请求取消收藏
            url = HttpAdress.CANCELCOLLECTION;
        }

        HttpUtils.post(url, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (item.getCollection() == 0) {
                    UiUtils.Toast("收藏失败," + BaseApplication.ERROR, false);
                } else if (item.getCollection() == 1) {
                    UiUtils.Toast("取消收藏失败," + BaseApplication.ERROR, false);
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (!TextUtils.isEmpty(response)) {
                    ResultInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }
                    if (null != info) {
                        if ("200".equals(info.state)) {
                            if (item.getCollection() == 0) {
                                item.setCollection(1);
                                cloneData.get(pos).setCollection(1);
                                UiUtils.Toast("收藏成功", false);
                            } else if (item.getCollection() == 1) {
                                UiUtils.Toast("取消收藏成功", false);
                                item.setCollection(0);
                                cloneData.get(pos).setCollection(0);
                            }
                            //通知适配器刷新数据
                            notifyDataSetChanged();

                        } else {
                            if (item.getCollection() == 0) {
                                UiUtils.Toast("收藏失败," + "异常码:" + info.state, false);
                                Log.i("test", "异常码是:" + info.state);
                            } else if (item.getCollection() == 1) {
                                UiUtils.Toast("取消收藏失败," + "异常码:" + info.state, false);
                                Log.i("test", "异常码是:" + info.state);
                            }
                        }
                    }

                }
            }
        });
    }
}